﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Configuration;

namespace Utils
{
    /// <summary>
    /// 封装了 日志操作  （密封类） author jianan.wang
    /// </summary>
    public sealed class DataLogHelper2
    {
        private static object LogFileObject = new object();

        #region 内部日志扩展

        /// <summary>
        /// Section配置节
        /// </summary>
        /// <returns></returns>
        private static IDictionary SectionConfig()
        {
            IDictionary dic = ConfigurationManager.GetSection("MultiFlagDataLogHelper") as IDictionary;
            return dic;
        }


        /// <summary>
        /// 获取最终路径
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        private static string GetNewFinallyPath(string path)
        {
            string Finalypath = string.Empty;
            Finalypath = path.IndexOf(":") > -1 ? path : System.Web.HttpContext.Current.Server.MapPath(path);
            Finalypath += "." + DateTime.Now.ToString("yyyyMMdd");

            if (SectionConfig() != null && SectionConfig()["LogFlag"] != null && string.IsNullOrWhiteSpace(SectionConfig()["LogFlag"].ToString()) == false)
            {

                Finalypath += "." + SectionConfig()["LogFlag"];
            }

            Finalypath += ".log";


            return Finalypath;
        }

        #endregion


        /// <summary>
        /// 记录日志
        /// </summary>
        /// <param name="log"></param>
        public static void WriteLog(string log)
        {
            string Client_logpath = ConfigurationManager.AppSettings["Client_logpath"];
            WriteLog(log, Client_logpath);
        }

        /// <summary>
        /// 记录日志
        /// </summary>
        /// <param name="log"></param>
        public static void WriteLog(string log, string Client_logpath)
        {
            System.IO.StreamWriter sw = null;

            //add  by  刘磊
            //BitAuto.EP.Plat.Util.DataLogHelper.D(log);

            if (Client_logpath != string.Empty)
            {

                try
                {
                    lock (LogFileObject)
                    {
                        string Finalypath = GetNewFinallyPath(Client_logpath);
                        sw = System.IO.File.AppendText(Finalypath);
                        sw.WriteLine(log);
                    }

                }
                catch
                {

                }
                finally
                {
                    if (sw != null)
                    {
                        sw.Flush();
                        sw.Close();
                    }
                }

            }
        }
    }
}
